package com.btb.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.btb.adapter.mapper.IpWhiteListDao;
import com.btb.adapter.mapper.UserApiDao;
import com.btb.adapter.utils.IPUtils;
import com.btb.adapter.utils.ResponseText;
import com.btb.adapter.utils.SignUtils;
import com.btb.core.exception.AuthException;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	private UserApiDao userApiDao;
	@Autowired
	private IpWhiteListDao ipWhiteListDao;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String requestURI = request.getRequestURI();
		if(!requestURI.startsWith("/api/")) {
			return true;
		}
		log.error("requestURI :{}", requestURI);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");

		String sign = request.getHeader("sign");
		if (StringUtils.isEmpty(sign)) {
			throw new AuthException("access denied code 100");
		}
		boolean checkSign = SignUtils.checkSign(sign);
		if (!checkSign) {
			throw new AuthException("access denied code 200");
		}
		if (!userApiDao.check(sign)) {
			throw new AuthException("access denied code 300");
		}
		String userIp = IPUtils.getRealIP(request);
		boolean check = ipWhiteListDao.check(userIp);
		if (!check) {
			log.error("AuthInterceptor userIp:{}", userIp);
			throw new AuthException("access denied code 400");
		}
		return true;
	}
}
